import tkinter as tk
import asyncio
import threading
import time
from ui.MainWindow import MainWindow
from utils.Logger import Logger
from config import Config
from services.AIServiceFactory import AIServiceFactory

def async_loop(loop):
    """运行异步事件循环"""
    asyncio.set_event_loop(loop)
    loop.run_forever()

def main():
    """主程序入口"""
    # 初始化日志
    logger = Logger(__name__)
    logger.info("Starting application...")
    
    # 创建并启动异步事件循环
    logger.debug("Starting async event loop...")
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    threading.Thread(target=async_loop, args=(loop,), daemon=True).start()
    logger.info("Async event loop started in background thread")
    
    # 确保事件循环已启动
    while not loop.is_running():
        time.sleep(0.1)
    
    try:
        # 初始化配置
        logger.debug("Loading configuration...")
        config = Config()
        logger.info(f"Configuration loaded from {config.config_file}")
        
        # 创建主窗口
        logger.debug("Creating main window...")
        root = tk.Tk()
        root.title("Markdown编辑器")
        root.geometry("1000x800")
        logger.debug("Main window created with size 1000x800")
        
        # 初始化AI服务
        logger.debug("Initializing AI service...")
        ai_service = AIServiceFactory.create_service(config, loop)
        logger.info(f"AI service initialized: {ai_service.__class__.__name__}")
        
        # 初始化主界面
        logger.debug("Initializing main window components...")
        main_window = MainWindow(root, ai_service, config)
        logger.info("Main window initialized successfully")
        
        # 启动主循环
        logger.info("Starting main loop")
        root.mainloop()
        logger.info("Main loop ended")
        
    except Exception as e:
        logger.critical(f"Application error: {str(e)}", exc_info=True)
        raise
    finally:
        logger.info("Application shutdown")
        Logger.cleanup_logs()

if __name__ == "__main__":
    main()
